package com.yzb.ftp;

import com.yzb.helper.FtpClientHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * <p>默认的ftp进度监听实现.</p>
 *
 * @author huang yu zhi
 * @version 1.0.0
 * @date 2019-01-29 16:32
 */
@Component
@Slf4j
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DefaultFtpProgressListener implements FtpProgressListener {
    /**spring ApplicationContext上下文.*/
    @Autowired
    private ApplicationContext applicationContext;

    /**上一次传输的字节百分比.*/
    private int lastPercent = 0;
    /**字节传输百分比的次数.*/
    private int times = 1;

    /**
     * 无参构造函数.
     */
    public DefaultFtpProgressListener() {
    }

    /**
     *
     * @param totalBytesTransferred 目前已传输的字节数
     * @param bytesTransferred 每次传输的字节数
     * @param totalBytes 总的字节数
     */
    @Override
    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long totalBytes) {
        int percent = (int) (totalBytesTransferred * 100 / totalBytes);
        if (percent >= FtpClientHelper.FTP_CONFIG.getIntervalProgress() * this.times) {
            this.times++;
            if (percent > this.lastPercent) {
                log.debug("已到达{}%,可以通知了",  percent);
                this.lastPercent = percent;
            }
        }
        if (percent == 100) {
            log.debug("已到达{}%,可以通知了", percent);
        }
    }
}
